package com.easou.ps.master.channel;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

import com.easou.ps.common.servicehandle.GBKCompactProtocol;
import com.easou.ps.common.servicehandle.ServiceAddress;
import com.easou.ps.thrift.qs.QSResult;
import com.easou.ps.thrift.qs.Query;
import com.easou.ps.thrift.qs.QueryRewriteType;
import com.easou.ps.thrift.qs.QueryType;
import com.easou.ps.thrift.search.rpc.WorkerRPC;
import com.easou.ps.thrift.search.types.IndexSearchRequest;
import com.easou.ps.thrift.search.types.WorkerSearchRequest;
import com.easou.ps.thrift.search.types.WorkerSearchResponse;
import com.easou.ps.thrift.search.types.WorkerSearchResult;
import com.easou.ps.utils.SubResult2SubSearchResult;
import com.easou.ps.webmaster.SearchRequest;
import com.easou.ps.webmaster.SearchResult;
import com.easou.ps.webmaster.SubSearchResult;

public class RequestChannel {
	public static List<SearchResult> toGet(SearchRequest request, QSResult qsResult) {
		ServiceAddress channelAddress = null;
		if (request.getPageNum() > 1) {
			return null;
		}
		/*WorkerSearchRequest workerReq = change2WorkerRequest(request,qsResult);
//		List<ServiceAddress> addresses = ServerAddressFactory.selectAddresses("Channel");
//		if(addresses!=null && addresses.size()>0){
//			channelAddress = addresses.get(0);
			channelAddress = new ServiceAddress("10.14.17.164", 10000);
			TTransport transport;
			try {
			    transport = new TSocket(channelAddress.getHost(), channelAddress.getPort());
			    TProtocol protocol = new GBKCompactProtocol(transport);
			    WorkerRPC.Client channelClient = new WorkerRPC.Client(protocol);
			    transport.open();
			    WorkerSearchResponse channelResponse = channelClient.search(workerReq);
			    transport.close();
			    return change2WorkerResponse(channelResponse);
			} catch (TTransportException e) {
			    e.printStackTrace();
			} catch (TException e) {
			    e.printStackTrace();
			}*/
//		}
		
		WorkerSearchRequest req = change2WorkerRequest(request,qsResult);
		IndexSearchRequest ireq = new IndexSearchRequest();
		Map<String, String> map = new HashMap<String, String>();
//		map.put("file", file);
//		map.put("req_type", "reload");
		
		ireq.queryStr = request.getQ();
		map.put("p", "1");
		map.put("wver", "3");
//		map.put("clearCache", "1");
		req.extendFields = map;
		req.request = ireq;
		//req.setQ("周杰伦");
//		req.setClearCache(1);
//		req.setPageNum(1);
//		req.setPageSize(6);
//		req.setDd("t");
//		req.setDebug(false);

		InetAddress addr = null;
		try {
			addr = InetAddress.getLocalHost();
		} catch (UnknownHostException e1) {
			return null;
		}
		String ip = addr.getHostAddress().toString();//获得本机IP
		
		HashMap<Integer, String> ipMap = new HashMap<Integer, String>();
		ipMap.put(1, "121.9.222.164");
		ipMap.put(2, "121.9.222.166");
		ipMap.put(3, "113.105.248.178");
		ipMap.put(4, "113.105.248.179");
		ipMap.put(5, "183.60.215.79");

		TSocket socket = new TSocket(ipMap.get(1), 10000);	

		TTransport readTrans = new TFramedTransport(socket, 3000000);
		TTransport writeTrans = new TFramedTransport(socket, 3000000);
		TProtocol readProt = new GBKCompactProtocol(readTrans);
		TProtocol writeProt = new GBKCompactProtocol(writeTrans);

		try {
			if(!writeProt.getTransport().isOpen()){
				writeProt.getTransport().open();
			}
			
			if(!readProt.getTransport().isOpen()){
				readProt.getTransport().open();
			}
			
			WorkerRPC.search_args argss = new WorkerRPC.search_args();
			argss.setReq(req);
			
			writeProt.writeMessageBegin(new org.apache.thrift.protocol.TMessage("search", org.apache.thrift.protocol.TMessageType.CALL, 0));
			argss.write(writeProt);
			writeProt.writeMessageEnd();
			writeProt.getTransport().flush();
			
			WorkerRPC.search_result result = new WorkerRPC.search_result();
			org.apache.thrift.protocol.TMessage msg = readProt.readMessageBegin();
    		if (msg.type == org.apache.thrift.protocol.TMessageType.EXCEPTION) {
    			org.apache.thrift.TApplicationException x = org.apache.thrift.TApplicationException.read(readProt);
    			readProt.readMessageEnd();
    			throw x;
    		}
    		
    		result.read(readProt);
    		readProt.readMessageEnd();
			WorkerSearchResponse response = result.success;
			return change2WorkerResponse(response);
    	} catch (Exception e) {
//			System.out.println(getName() + ":ConnectionGuard run() caught exception:" + e);
			e.printStackTrace();
    	} finally {
//	    	pool.invalidateConnection(this);
//    		close();
    		readTrans.close();
    		writeTrans.close();
    		socket.close();
    	}
		return null;
	}
	
	private static WorkerSearchRequest change2WorkerRequest(SearchRequest request, QSResult qsResult) {
		WorkerSearchRequest result = new WorkerSearchRequest();
		Map<String, String> extendAttr = new HashMap<String, String>();
		extendAttr.put("wver", "" + request.getViewVersion());
		extendAttr.put("p", "" + request.getPageNum());
		extendAttr.put("r", "" + 0);
		extendAttr.put("clearCache", "" + request.getClearCache());
		if(request.getLocalCity()!=null){
			extendAttr.put("localCity", request.getLocalCity());	
		}
		if(request.getLocalCode()!=null){			
			extendAttr.put("localCode", request.getLocalCode());
		}
		Query query = qsResult.getQuerys().get(QueryRewriteType.Normal);
		
		if(query != null && getQueryType(query) != null){
			extendAttr.put("queryType", getQueryType(query));
		}
		result.setOsType(request.getOsType());
		result.setExtendFields(extendAttr);
		
		IndexSearchRequest indexSearchRequest = new IndexSearchRequest();
		result.setRequest(indexSearchRequest);
		
		return result;
	}

	private static List<SearchResult> change2WorkerResponse(WorkerSearchResponse channelResponse) {
		List<SearchResult> searchResults = new ArrayList<SearchResult>();
		
		if(channelResponse == null || channelResponse.getResultsSize()<1){
			return null;
		}else{
			List<WorkerSearchResult> workerSearchResults = channelResponse.getResults();
			for (int i = 0; i < workerSearchResults.size(); i++) {
				SearchResult result = new SearchResult();
				result.setTitle(workerSearchResults.get(i).getExtendFields().get("title"));
				result.setUrl(workerSearchResults.get(i).getExtendFields().get("url"));
				result.setHost(workerSearchResults.get(i).getExtendFields().get("host"));
				result.setType(workerSearchResults.get(i).getExtendFields().get("type"));
				result.setSummary(workerSearchResults.get(i).getExtendFields().get("summary"));
				result.setSummary2(workerSearchResults.get(i).getExtendFields().get("summary2"));
				if(workerSearchResults.get(i).getExtendFields().get("summaryflag")!=null){			
					try {
						int summaryFlag = Integer.valueOf(workerSearchResults.get(i).getExtendFields().get("summaryflag"));
						result.setSummaryflag(summaryFlag);
					} catch (NumberFormatException e) {
						result.setSummaryflag(0);
					}
				}
				result.setScore(workerSearchResults.get(i).getResult().getScore());
				result.setExtendFields(workerSearchResults.get(i).getExtendFields());
				result.setLinks(workerSearchResults.get(i).getLinks());
				result.putToExtendFields("source", "channel");//这个字段后期要统一到workerType
				result.putToExtendFields("workerType", "Channel");
				List<SubSearchResult> change2SubResult = SubResult2SubSearchResult.convert2SubSearchResult(workerSearchResults.get(i).getSubResult());
				if(change2SubResult != null){
					result.setSubResult(change2SubResult);
				}
				//result.setWapType(getWapTypeByValue(workerSearchResult.getExtendFields().get("wapTypeStr")));
				searchResults.add(result);
			}
		}
		return searchResults;
	}
	
	private static String getQueryType(Query query) {
		String result = "";
		List<QueryType> query_types = query.getTypes();
		if (query_types == null) {
			return result;
		}
		for (int i = 0; i < query_types.size(); i++) {
			QueryType query_type = query_types.get(i);
			if (query_type != null) {
				result += "|" + query_type.getType() + "(热度：" + query_type.getHot() + ";实体：" + query_type.getEntity() + ")";
			}
		}
		if (result.length() > 1) {
			return result.substring(1);
		} else {
			return result;
		}
	}
}
